/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ruoyi.common.utils.jxls;

import java.util.ArrayList;
import java.util.List;

import static org.apache.commons.collections4.CollectionUtils.isNotEmpty;

/**
 * 此类用于分页，就是把从数据库查询出来的一个完整的List链表变成一截一截是数据。
 *
 * @author foxlee1024
 */
public class DataByPage {

    static int pagesize = 3; // 每页记录数

    /**
     * 根据每页显示多少条数据计算总页数
     *
     * @param dataList 数据库查询的数据
     */
    private static int countPages(List<?> dataList) {
        int recordcount = isNotEmpty(dataList) ? dataList.size() : 0; // 总记录数
        return (recordcount + pagesize - 1) / pagesize;
    }

    public static List<Page> byPage(List<?> dataList) {
        List<Page> pageList = new ArrayList<>(); // 页面分页
        if (isNotEmpty(dataList)) {
            int pagecount = countPages(dataList); // 总页数
            int nowDataListPoint = 0; // 读取到接收的哪一条数据
            final int recordCount = isNotEmpty(dataList) ? dataList.size() : 0;
            for (int i = 0; i < pagecount; i++) {
                List<Object> pagedata = new ArrayList<>();
                // 把传来的数据取出
                while (nowDataListPoint < recordCount) {
                    pagedata.add(dataList.get(nowDataListPoint));
                    nowDataListPoint += 1;
                    if (nowDataListPoint != 0 && nowDataListPoint % pagesize == 0) {
                        break;
                    }
                }
                Page page = new Page("page_" + (i + 1), (i + 1) + "", pagecount + "", pagedata);
                pageList.add(page);
            }
        }
        return pageList;
    }
}
